package com.mocai.merchant.controller;

import com.mocai.merchant.model.User;
import com.mocai.merchant.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/1/8.
 */
@Controller
public class LoginController {

    @Autowired
    UserService userService;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String toLogin() {
        return "demo/ztree/login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Object doLogin(HttpServletRequest request, String username, String password) {
        Map<Object, Object> returnValue = new LinkedHashMap<>();
        User user = userService.findByUsernameAndPassword(username, password);
        if (null != user) {
            HttpSession session = request.getSession(true);
            session.setAttribute("user", user);
        }
        returnValue.put("user", user);
        return returnValue;
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String doLogout(HttpServletRequest request) {
        request.getSession().invalidate();
        return "redirect:/login";
    }

}
